/**
 * Created with JetBrains PhpStorm.
 * User: jiangshuguang
 * Date: 14-5-11
 * Time: 下午10:13
 * To change this template use File | Settings | File Templates.
 * 公共方法
 */


var toString = Object.prototype.toString;

exports.util = {

    /**
     * 浮点型保留精度
     * @param src
     * @param pos
     * @returns {number}
     */
    formatFloat : function(src, pos){
        return Math.round(parseFloat(src)*Math.pow(10, pos))/Math.pow(10, pos);
    },

    /**
     * 日期格式时间转化为时间戳
     * @param str
     * @returns {number}
     */
    strToTimeStamp:function(str){
        var date = new Date(str);
        return date.getTime();
    },

    /**
     * 判断是否在数组中
     * @param val
     * @param arr
     * @returns {boolean}
     */
    inArray:function(val,arr){
        for(var i= 0,len=arr.length;i<len;i++){
            if(val == arr[i]){
                return true;
            }
        }
        return false;
    },

    /**
     * 对特殊字符进行过滤
     * @param source
     * @returns {string}
     */
    escape : function (source) {
        return String(source)
            .replace(/&/g,'&amp;')
            .replace(/</g,'&lt;')
            .replace(/>/g,'&gt;')
            .replace(/\\/g,'&#92;')
            .replace(/"/g,'&quot;')
            .replace(/'/g,'&#39;');
    },

    /**
     * 将时间戳转化为时间
     * @param ns 时间戳
     * @param formatA 格式 yyyy-MM-dd hh:mm:ss
     * @returns {string}
     */
    toTime : function(ns,formatA){
        var time,format,o;
        time = new Date(ns);
        format = formatA?formatA:"yyyy-MM-dd";
        o ={
            "M+" : time.getMonth()+1,
            "d+" : time.getDate(),
            "h+" : time.getHours(),
            "m+" : time.getMinutes(),
            "s+" : time.getSeconds(),
            "q+" : Math.floor((time.getMonth()+3)/3),
            "S" : time.getMilliseconds()
        };
        if(/(y+)/.test(format)){
            format = format.replace(RegExp.$1, (time.getFullYear()+"").substr(4 - RegExp.$1.length));
        }
        for(var k in o){
            if(o.hasOwnProperty(k)){
                if(new RegExp("("+ k +")").test(format)){
                    format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
                }
            }
        }
        return format;
    },

    /**
     * 判断类型,比typeof instansof靠谱
     * @param source
     * @param type
     * @returns {boolean}
     */
    is:function(source, type){
        console.log(type);
        return toString.call(source) === '[object ' + type + ']';
    },

    /**
     * todo
     * 简单的对象扩展，不支持二层级的对象
     * @param self
     * @returns {*}
     */
    extend:function(self){
        for(var i=0,len=arguments.length;i<len;i++){

        }
        return self;
    },

    /**
     * todo
     * 对象clone
     * @param source
     * @returns {*}
     */
    clone:function(source){
        var me = this,
            ret,
            type = toString.call(source);

        if(type == "[object Object]"){

        }else if(type == "[object Array]"){

        }else{
            return source;
        }
    },

    /**
     * 对url进行分析
     */
    getUrlParas:function(){
        var args = {},
            query = location.search.substring(1),
            pairs = query.split("&"),
            href = location.href,
            hashs = href.split("#");
        for(var i = 0; i < pairs.length; i++) {
            var pos = pairs[i].indexOf('=');
            if (pos == -1) continue;
            var argname = pairs[i].substring(0,pos);
            var value = pairs[i].substring(pos+1);
            value = decodeURIComponent(value);
            args[argname] = value;
        }

        if(hashs.length>=2){
            args["_hash"] = hashs[1];
        }else{
            args["_hash"] = "";
        }
        return args;
    },

    setCookie : function(cookieString,time){
        var date=new Date();
        date.setTime(date.getTime()+30*24*3600*1000);
        cookieString=cookieString+"; expires="+date.toGMTString();
        document.cookie = cookieString;
    },

    readCookie : function(key){
        var cookiestr = document.cookie,
            cookiearr = cookiestr.split(";");
        for(i=0; i<cookiearr.length; i++){
            var cookie_key = cookiearr[i].split("=")[0];
            cookie_key = cookie_key.replace(/\s*/g,"");
            if(key == cookie_key){
                return cookiearr[i].split("=")[1];
            }
        }
        return null;
    },

    /**
     * 删除cookie
     * @param key
     */
    delCookie : function(key){
        var expire_time = new Date();
        expire_time.setFullYear(expire_time.getFullYear() - 1);
        document.cookie = " " + key + "=e;expires=" + expire_time + ";";
    },

    /**
     * todo 需要完善
     * 模拟a标签，大都是为了统计需要
     * @param $this
     */
    refresh:function($this){
        if(!!$this.attr("href")){
            if($this.attr("target")==="_blank"){
                window.open($this.attr("href"));
            }else{
                location.href=$this.attr("href");
            }
        }
    },

    /**
     * 多边形的中心点
     * @param points
     * @returns {*}
     */
    polygonCenter:function(points){
        var x = 0,
            y = 0,
            len = points.length;
        if(len){
            for(var i=0;i<len;i++){
                x+=points[i][0];
                y+=points[i][1];
            }
            return [x/len,y/len];
        }else{
            return false;
        }
    },

    /**
     * firefox不支持offsetX & offsetY
     * @param {event} e
     * @returns {*}
     */
    getOffset : function(e){
        if(/Firefox\/([\d.]+)/.test(navigator.userAgent)){
            var target = e.target,
                getPageCoord = function(element){
                    var coord = {x: 0, y: 0};
                    while (element){
                        coord.x += element.offsetLeft;
                        coord.y += element.offsetTop;
                        element = element.offsetParent;
                    }
                    return coord;
                };
            if(target.offsetLeft == undefined){
                target = target.parentNode;
            }
            var pageCoord = getPageCoord(target),
                eventCoord ={
                    x: window.pageXOffset + e.clientX,
                    y: window.pageYOffset + e.clientY
                };
            return {
                offsetX: eventCoord.x - pageCoord.x,
                offsetY: eventCoord.y - pageCoord.y
            };
        }else{
            return {
                offsetX:e.offsetX,
                offsetY:e.offsetY
            }
        }
    },

    //地图各个级别下一经纬度的像素跨度
    pointPixelMap:{
        18:{x:111320,y:142760},
        17:{x:55660,y:71380},
        16:{x:27830,y:35690},
        15:{x:13915,y:17961},
        14:{x:6957,y:8980},
        13:{x:3479,y:4490},
        12:{x:1740,y:2245},
        11:{x:869.7,y:1209.2},
        10:{x:434.9,y:604.6},
        9:{x:217.4,y:302.3},
        8:{x:108.72,y:151.94},
        7:{x:54.36,y:75.98},
        6:{x:27.18,y:37.98},
        5:{x:13.58,y:19},
        4:{x:6.8,y:9.5},
        3:{x:3.4,y:4.74}
    },

    /**
     * 点是否在多边形内
     * @param point [x,y]
     * @param polygon [[x1,y1],[x2,y2] ...]
     * @param rank  调整水平辅助线范围 默认-180
     * @returns {boolean}
     */
    isPointInPolygon : function(point,polygon,rank){
        var crossMul,checkCross,p1,p2,p3,p4,count=0;
        crossMul = function(v1,v2){
            return   v1[0]*v2[1]-v1[1]*v2[0];
        };
        checkCross = function(p1,p2,p3,p4){
            var v1=[p1[0]-p3[0],p1[1]-p3[1]],
                v2=[p2[0]-p3[0],p2[1]-p3[1]],
                v3=[p4[0]-p3[0],p4[1]-p3[1]],
                v=crossMul(v1,v3)*crossMul(v2,v3);
            v1=[p3[0]-p1[0],p3[1]-p1[1]];
            v2=[p4[0]-p1[0],p4[1]-p1[1]];
            v3=[p2[0]-p1[0],p2[1]-p1[1]];
            return !!(v<=0&&crossMul(v1,v3)*crossMul(v2,v3)<=0);
        };

        p1=point;
        p2=[rank?rank:-180,point[1]];
        for(var i=0;i<polygon.length-1;i++){
            p3=polygon[i];
            p4=polygon[i+1];
            if(p3[1] == p4[1]){
                continue;
            }
            if(p1[1]<(p3[1]<p4[1]?p3[1]:p4[1]) || p1[1]>=(p3[1]>p4[1]?p3[1]:p4[1])){
                continue;
            }
            if(checkCross(p1,p2,p3,p4)==true){
                count++
            }
        }
        p3=polygon[polygon.length-1];
        p4=polygon[0];
        if(checkCross(p1,p2,p3,p4)==true){
            count++
        }
        return !(count%2==0)
    }
};
